<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()

import { OrderNavOptions } from '@/services/constants'

import { MedicineOrderStatus } from '@/enums'
import { getMedicineOrderList } from '@/services/order'
import type { MedicineOrderItem } from '@/types/order'

const active = ref<MedicineOrderStatus>(10)

const current = ref(1)

const loading = ref(false)

const finished = computed(() => current.value >= pageTotal.value)

const pageTotal = ref(0)

const medicineOrderList = ref<MedicineOrderItem[]>([])

const getOrderList = async (val: boolean = true) => {
  loading.value = true
  if (val) {
    current.value = 1
    medicineOrderList.value = []
  }
  try {
    const { data } = await getMedicineOrderList(current.value, active.value)
    pageTotal.value = data.pageTotal
    medicineOrderList.value = medicineOrderList.value.concat(data.rows)
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
  if (pageTotal.value > current.value) {
    current.value += 1
  }
}

onMounted(() => {
  route.query.status && (active.value = +route.query.status as number)
  getOrderList()
})
</script>

<template>
  <div class="order-list-page">
    <cp-nav-bar title="药品记录" />
    <van-tabs v-model:active="active" @change="getOrderList">
      <van-tab
        v-for="item in OrderNavOptions"
        :key="item.status"
        :title="item.label"
        :name="item.status"
      ></van-tab>
    </van-tabs>

    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      :offset="50"
      @load="() => getOrderList(false)"
    >
      <van-cell
        v-for="item in medicineOrderList"
        :key="item.id"
        :title="item.id"
      />
    </van-list>
  </div>
</template>

<style scoped lang="scss">
.order-list-page {
  padding-top: 46px;
}
</style>
